<template>
    <div class="timekeep">
        <titleBar title="计时器" theme="dark" :noFixed="true" />
        <div class="inner">
            <div class="orderCard bgdark" v-if="orderAllInfo">
                <div class="top">
                    <div class="name fz2">{{orderAllInfo.orderName}}</div>
                    <div class="content flex fz4">
                        <div class="wordsGray">作图数量</div>
                        <div>{{orderAllInfo.pictureNum}}天</div>
                    </div>
                    <div>
                        <div class="content flex fz4">
                            <div class="wordsGray">初次上门</div>
                            <div>{{orderAllInfo.homeTime}}</div>
                        </div>
                        <div class="content flex fz4">
                            <div class="wordsGray">预约日期</div>
                            <div>{{orderAllInfo.appointmentTime.join('、')}}</div>
                        </div>
                        <div class="content flex fz4">
                            <div class="wordsGray">约定地点</div>
                            <div>{{orderAllInfo.address}}</div>
                        </div>
                    </div>
                </div>
                <div class="rightimg">
                    <img src="@/assets/img/performance/orderCard/doNow3.png" width="100%" />
                </div>
                <div class="msg" @click="go_chat(orderAllInfo.groupUid)">
                    <div class="dot" v-if="groupUids && groupUids.includes(orderAllInfo.groupUid)">
                        <img src="@/assets/img/performance/orderCard/dot.png" width="100%" alt="">
                    </div>
                    <img src="@/assets/img/performance/orderCard/dark-message-icon.png" width="100%" alt="">
                </div>
            </div>
            <div class="title-name">{{
                !type ? '准备开启' :
                type === 'stop' ? '已暂停' :
                type === 'start' ? '计时中' :
                '准备开启'
            }}</div>
            <div class="flex timekepping-show flex-center-x flex-center-y">
                <div class="block">{{timekeepDate.h}}</div>
                <div class="gap">:</div>
                <div class="block">{{timekeepDate.m}}</div>
                <div class="gap">:</div>
                <div class="block">{{timekeepDate.s}}</div>
            </div>
            <div class="flex handle-box" v-if="type">
                <div class="button b-stop" v-on:click="onstop" v-if="type === 'start'">暂停</div>
                <div class="button b-continue" v-on:click="oncontinue" v-if="type === 'stop'">继续</div>
                <div class="button b-done" v-on:click="done">完成</div>
            </div>
            <div v-else class="flex handle-box flex-center-x">
                <div class="button b-ready">待确认</div>
            </div>
        </div>
    </div>
</template>
<script>
import titleBar from '@/components/title_bar/index.vue'
import { Timekeep, HMS2S } from '@/utils/date.js'
import { Copy } from '@/utils/object.js'
import { getRole, getuserUid,getUserLogin } from '@/utils/auth.js'
import { setRemind, getRemind } from "@/utils/chat.js";

export default {
    components: {
        titleBar,
    },
    data(){
        return {
            timekeepDate: {h: '00', m: '00', s: '00'},
            type: '',
            timekeep: null,
            orderAllInfo: null,
            groupUids: getRemind(),
            loadingType: -1
        }
    },
    // TODO app上可能会涉及到睡眠等问题
    created(){
        this.initData()
    },
    methods: {
        async initData(){
            // TEST location.href = 'http://localhost:8080/#/timekeep?uid=e8c11f24d5c14b1089e2d8eb420c3b09&buseruid=834532c343a911e9855d6045cb8a6182'
            let orderUid = this.$route.query?.uid
            let bUserUid = getuserUid() //this.$route.query?.buseruid
            // let preordainDate = this.$route.query?.date
            // await new Promise(e => {
            //     window.setTimeout(() => {
            //         e()
            //     }, 3e3)
            // })
            if(!orderUid){
                this.$toast('UID不存在')
                return
            }
            if(!bUserUid){
                this.$toast('表现师UID不存在')
                return
            }
            let params = {
                uid: orderUid,
                role: getRole()
                // preordainDate,
            }
            // 表现师计时
            this.timekeep = Timekeep()
            this.orderUid = orderUid
            this.bUserUid = bUserUid
            this.loadingType = 1
            let timekeepInfo = await HTTP('order_detail', params)
            if(timekeepInfo.code !== 200){
                this.$toast(timekeepInfo.msg || '服务器异常')
                this.loadingType = 3
            }
            this.loadingType = 2
            let info = timekeepInfo.data
            this.orderAllInfo = Copy(timekeepInfo.data)
            // console.log('表现师计时信息')
            // console.log(timekeepInfo.data)
            let start = (addNumber) => {
                this.timekeep.start((e) => {
                    this.loadingType = 22
                    this.timekeepDate = e
                    // console.log('计时时间')
                    // console.log(e)
                    if((+e.s) % 5 == 0 && (+e.s) != 0){
                        setTimeout(() => {
                            // 结束并释放资源
                            this.timekeep.end()
                            this.initData()
                        }, 2e3)
                    }
                }, {
                    n: HMS2S(info.totalTime, ':') + addNumber
                })
            }
            // 消息红点
            if(true){
                // TODO 
            }

            if(info.chronographStatus === 1){
                console.log('待开始')
                return
            }
            if(info.chronographStatus === 2){
                console.log('计时中')
                this.type = 'start'
                start(0)
                return
            }
            if(info.chronographStatus === 3){
                console.log('暂停中')
                // 模拟请求
                this.type = 'stop'
                start(-1)
                setTimeout(() => {
                    this.timekeep.stop()
                }, 1e3 + 20)
                return
            }
            if(info.chronographStatus === 4){
                console.log('已完成')
                return
            }
        },
        //跳转聊天室
        go_chat(id) {
            console.log(this.orderAllInfo)
            if(!this.orderAllInfo){
                this.$toast('数据未加载完成')
                return
            }
            // (form.groupUid,form.uid)
           if(this.groupUids){
                this.groupUids.includes(id) && this.groupUids.splice(this.groupUids.findIndex(gid => gid == id), 1);
            }
            setRemind(this.groupUids);
            this.$router.push({
                path: "/performance/chat", query: {
                    id: this.orderAllInfo.groupUid,
                    orderId: this.orderAllInfo.uid
                }
            })
        },
        isReadyRun(){
            console.log(this.loadingType)
            return this.loadingType !== 22
        },
        async onstop(){
            if(this.isReadyRun()){
                console.log('未开始')
                return
            }
            this.timekeep.stop()
            this.$toast.loading({
                duration: 0,
                // forbidClick: true,
                mask: true,
                loadingType: 'spinner',
                message: '暂停'
            })
            let params = {
                bUserUid: this.bUserUid,
                orderUid: this.orderUid,
            }
            let response
            try {
                // await new Promise(e => window.setTimeout(e, 500))
                response = await HTTP('app/buser/timeStopOrder', params)
                console.log('--response--')
                console.log(response)
                if(response.code !== 200){
                    this.$toast(response.msg || '服务器异常')
                }
                
                this.$toast.clear()
                this.type = 'stop'
                //环信消息通知
                let extObj = { 
					type: "timerPause", 
					name: getUserLogin().userName,
					time:Date.parse(new Date())
				};
                let ext = JSON.stringify(extObj);
            
                let res = await HTTP("chat_send_msg", {
                    content:"暂停计时",
                    userUid: getuserUid(),
                    groupUid: this.orderAllInfo.groupUid,
                    ext,
                    roomType: "group"
                });
            } catch (error) {
                console.log(error)
                this.$toast('数据开小差了')
                this.$toast.clear()
                this.type = 'stop'
                return
            }
        },
        async oncontinue(){
            if(this.isReadyRun()){
                console.log('未开始')
                return
            }
            this.$toast.loading({
                duration: 0,
                // forbidClick: true,
                mask: true,
                loadingType: 'spinner',
                message: '继续'
            })
            
            let params = {
                bUserUid: this.bUserUid,
                orderUid: this.orderUid,
            }
            try {
                await new Promise(e => window.setTimeout(e, 500))
                let response = await HTTP('app/buser/timeStopOrder', params)
                if(response.code !== 200){
                    this.$toast(response.msg || '服务器异常')
                }
                this.timekeep.continue()
                this.$toast.clear()
                this.type = 'start'
                //环信消息通知
                let extObj = { type: "timerContinue", name: getUserLogin().userName };
                let ext = JSON.stringify(extObj);
            
                let res = await HTTP("chat_send_msg", {
                    content:"继续计时",
                    userUid: getuserUid(),
                    groupUid: this.orderAllInfo.groupUid,
                    ext,
                    roomType: "group"
                });
            } catch (error) {
                console.log(error)
                this.$toast('数据开小差了')
                this.$toast.clear()
                return
            }
        },
        async done(){
            if(this.isReadyRun()){
                console.log('未开始')
                return
            }
            console.log('完成')
            this.$dialog.confirm({
                title: '提示',
                message: '是否确认该笔订单已全部完成，完成后不可撤销'
            }).then(async () => {
                console.log('done')
                let params = {
                    bUserUid: this.bUserUid,
                    orderUid: this.orderUid,
                }
                try {
                    let responseData = await HTTP('app/buser/timeEnd', params)
                    if(responseData.code !== 200){
                        this.$toast(responseData.msg || '服务器异常')
                    }
                    console.log(responseData.data)
                    // 完成时暂停计时
                    this.timekeep.stop()
                    //环信消息通知
                    let extObj = { type: "timerFinish", name: getUserLogin().userName };
                    let ext = JSON.stringify(extObj);
                
                    let res = await HTTP("chat_send_msg", {
                        content:"完成计时",
                        userUid: getuserUid(),
                        groupUid: this.orderAllInfo.groupUid,
                        ext,
                        roomType: "group"
                    });
                    // 给出提示，点击返回上一页
                    this.$dialog.alert({
                        title: '已完成',
                        message: '已完成计时，点击确定返回上一页'
                    }).then(() => {

                        this.$router.go(-1)
                    })
                } catch (error) {
                    console.log(error)
                    this.$toast('数据开小差了')
                }
            }).catch(() => {
                console.log('cancel')
            })
        }
    },
    destroyed(){
        // 结束并释放资源
        this.timekeep.end()
    }
}
</script>
<style lang="scss" scoped>
.timekeep{
    width: 100%;
    height: 100vh;
    overflow: auto;
    background-color: #282828;
    color: #fff;
    .inner{
        // margin-top: 
        // position: relative;
        // top: $title_bar_height;
        // transform: translate(0px, $title_bar_height);
        .title-name{
            text-align: center;
            margin-top: 1.20rem;
            font-size: .36rem;
        }
        .timekepping-show{
            width: 100%;
            margin-bottom: 1.26rem;
            margin-top: .5rem;
            .block{
                width: 1.31rem;
                height: 1.31rem;
                border-radius: .05rem;
                font-size: .48rem;
                text-align: center;
                line-height: 1.31rem;
                background-color: rgb(68, 68, 68)
            }
            .gap{
                width: .44rem;
                text-align: center;
                font-size: .35rem;
            }
        }
        .handle-box{
            .button{
                width: 2rem;
                height: 2rem;
                text-align: center;
                line-height: 2rem;
                border-radius: 50%;
                font-size: .36rem;
            }
            .b-stop{
                background: #FF5959;
                margin-left: 1.25rem;
                margin-right: 1rem;
            }
            .b-continue{
                background: #FFBA5A;
                margin-left: 1.25rem;
                margin-right: 1rem;
            }
            .b-done{
                background: #5E8EFE;
            }
            .b-ready{
                background: #aaa;
            }
        }
        .orderCard {
            position: relative;
            width: 94%;
            margin: auto;
            // box-shadow: 0px 2px 8px 4px rgba(216, 216, 216, 0.5);
            border-radius: 10px;
            overflow: hidden;    
            margin-top: 0.35rem;
            .top {
            padding: 0.4rem 0.24rem;
            .name {
                font-weight: bold;
                margin-bottom: 0.1rem;
                width: calc(100% - 1.4rem);
                height: 0.58rem;
                overflow: hidden; /*超出部分隐藏*/
                white-space: nowrap; /*不换行*/
                text-overflow: ellipsis; /*超出部分文字以...显示*/
            }
            .content {
                margin-top: 0.2rem;
                div:first-child {
                width: 1.35rem;
                }
                div:last-child {
                flex: 1;
                }
            }
            }
            .bot {
            background-color: #eff4ff;
            height: 1.08rem;
            //
            .botleft {
                width: 50%;
                align-items: center;
                justify-content: center;
                .tit {
                margin-right: 0.15rem;
                }
                .timeclock {
                width: 0.6rem;
                height: 0.6rem;
                border-radius: 6px;
                font-weight: 600;
                text-align: center;
                line-height: 0.6rem;
                }
                .bgstart {
                background-color: #dfe8ff;
                }
                .dots1 {
                color: #dfe8ff;
                font-weight: 600;
                }
                .dots {
                font-weight: 600;
                }
            }
            .botright {
                align-items: center;
                justify-content: center;
                width: 50%;
                .arrowRight {
                position: relative;
                top: 0.03rem;
                width: 0.24rem;
                margin-left: 0.16rem;
                }
                .service {
                height: 1.08rem;
                line-height: 1.08rem;
                width: 100%;
                text-align: center;
                background-color: #dfe8ff;
                font-weight: 600;
                }
                /* 已关闭 */
                .close {
                height: 1.08rem;
                line-height: 1.08rem;
                width: 100%;
                text-align: center;
                }
                /* 待签到 */
                .nosign {
                color: #cccccc;
                }
                /* 待开始 */
                .rbgstart {
                width: 100%;
                height: 100%;
                line-height: 1.08rem;
                text-align: center;
                background-color: #dfe8ff;
                }
            }
            .unclick {
                    background-color: #dfe8ff;
                }
            }
            .rightimg {
                position: absolute;
                width: 1.2rem;
                top: 0;
                right: 0;
            }
            .msg {
                position: absolute;
                width: 0.9rem;
                top: 1rem;
                right: 0.3rem;
                .dot {
                    position: absolute;
                    right: 0.12rem;
                    top: 0.12rem;
                    width: 0.22rem;
                }
            }
        }
        .bgdark{
            background-color: #444;
        }
    }
}
</style>


